<?php
/**
 * Created by YuanPan.
 * User: YuanPan
 * Date: 2018/5/12
 * Time: 19:08
 */

namespace app\api\service;


use app\api\lib\exception\MissException;
use app\api\lib\exception\SuccessMessage;
use app\api\lib\exception\TokenException;
use think\Cache;
use think\Request;

class TokenService
{
    /*
     * 生成自定义的加密随机加密字符串
     */
    public static function generateToken()
    {
        //32个字符生成一组随机字符串
        $randChars = getRandChar(32);
        $timestamp = time();
        $salt = config('secure.token_salt');
        return md5($randChars.$timestamp.$salt);
    }

    //获取指定缓存中的值
    public static function getCurrentTokenVar($key)
    {
        //获取用户携带的加密token值
        $token = request()->header('token');
        //从缓存中获取，并且看是否存在，不存在抛出异常
        $vars = cache($token);
        if(!$vars){
            throw new TokenException();
        }else{
            //按常理不需要判断是否为数组，存tp自带的缓存是json，不过发现如果存在redis就会变为数组，所以这里做下判断
            if(!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw new MissException([
                    'msg'=>'尝试获取的token变量并不存在',
                ]);
            }
        }
    }

    //剖离出来的，从缓存中获取用户id
    public static function getCurrentUid()
    {   //获取到用户的uid
        $uid = self::getCurrentTokenVar('uid');
        return $uid;
    }


    //检测用户是否登录
    public static function checkLogin()
    {
        $token = Request::instance()
            ->header('token');
        $vars = Cache::get($token);
        if (!$vars)
        {
            throw new TokenException();
        }else{
            return true;
        }
    }
    
    //验证token
    public static function verifyToken($token)
    {
        $token = cache($token);
        if($token){
            throw new SuccessMessage();
        }else{
            throw new TokenException();
        }
    }
}